package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.Key;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.bean.Status;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.KeyManager;
import com.dotstone.chipism.util.MyDBHelper;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
//import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class RemoteFanActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private Button mPowerB;
	private TextView mTitleTv;
	private boolean power = true;
	private Button mWindB;
	private Button mTimeB;
	private Button mShakeB;
	private Button mMoreB;
	private List<Key> keys = new ArrayList<Key>();
	private List<Key> moreKeys = new ArrayList<Key>();
	private List<Button> buttons = new ArrayList<Button>();
	private HashMap<Integer, String> cmdMaps = new HashMap<Integer, String>();
	private MySocket socket;
	private Vibrator vibrator;
	private Device device;
	private Dialog dialog;
	private GridView mKeysG;
	private KeyAdapter mAdapter;
	private MyDBHelper myDBHelper;
	private Status status;
	
	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.power_b:
			// 800 4000
			if (power) { // 当前打开 发送关指令
				mPowerB.setBackgroundResource(R.drawable.kaiguan22x);
				if (cmdMaps.get(4000) == null || cmdMaps.get(4000) == "") {
					sendCmd(cmdMaps.get(800));
				} else {
					sendCmd(cmdMaps.get(4000));
				}

				resetButton(false);
			} else { // 当前关闭 发送开的指令
				mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
				sendCmd(cmdMaps.get(800));
				resetButton(true);
			}
			power = !power;
			if (power) {
				myDBHelper.updateStatus(device.getDeviceID(), 0, 0, 0, 0);
			} else {
				myDBHelper.updateStatus(device.getDeviceID(), 1, 0, 0, 0);
			}
			vibrator.vibrate(50);
			break;
		case R.id.wind_btn:
			// 838
			sendCmd(cmdMaps.get(837));
			vibrator.vibrate(50);
			break;
		case R.id.time_btn:
			// 876
			sendCmd(cmdMaps.get(876));
			vibrator.vibrate(50);
			break;
		case R.id.shake_btn:
			// 836
			sendCmd(cmdMaps.get(836));
			vibrator.vibrate(50);
			break;
		case R.id.more_btn:
			// ToastShow.Show(getApplicationContext(), "无更多按键");
			initDialog();
			break;
		default:
			break;
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_fan;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mPowerB = $(R.id.power_b);
		mTimeB = $(R.id.time_btn);
		mWindB = $(R.id.wind_btn);
		mShakeB = $(R.id.shake_btn);
		mMoreB = $(R.id.more_btn);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		int position = getIntent().getIntExtra("position", -1);
		if (position != -1) {
			device = DeviceManager.getInstance().getRemotes().get(position);
		} else {
			String id = getIntent().getStringExtra("id");
			device = DeviceManager.getInstance().getDeviceById(id);
		}
		myDBHelper = new MyDBHelper(getApplicationContext());
		status = myDBHelper.getStatusById(device.getDeviceID());
		mTitleTv.setText(device.getDeviceName());
		socket = SocketManager.getInstance().sMap.get(device.getMainDeviceId());
		if (socket == null) {
			ToastShow.Show(getApplicationContext(), "该设备无绑定网关，无法被控制！");
			finish();
		}
		// 初始化按键
		initKey();
		if (status != null) {
			initStatus();
		}
		boolVersion();
		mBackL.setOnClickListener(this);
		mTimeB.setOnClickListener(this);
		mWindB.setOnClickListener(this);
		mShakeB.setOnClickListener(this);
		mMoreB.setOnClickListener(this);
		mPowerB.setOnClickListener(this);
	}
	
	private void initStatus(){
		if(status.isPower()){
			mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
			power = true;
		}else{
			mPowerB.setBackgroundResource(R.drawable.kaiguan22x);
			power = false;
		}
	}

	private void initDialog() {
		// TODO Auto-generated method stub
		dialog = new Dialog(RemoteFanActivity.this, R.style.MyDialogStyle);
		dialog.setContentView(R.layout.dialog_more_key);
		Window dialogWindow = dialog.getWindow();
		mKeysG = (GridView) dialog.findViewById(R.id.key_gv);
		mAdapter = new KeyAdapter();
		mKeysG.setAdapter(mAdapter);
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = LayoutParams.FILL_PARENT;
		dialogWindow.setAttributes(lp);
		dialog.show();
	}

	/**
	 * 初始化按键 将按键放入hash表 将控件放入集合 遍历 根据其tag找出cmdMaps中对应的cmd 如果没有cmd 将该按键设为不可点击
	 * 将背景图片该为暗灰色 判断遥控器的按键集合是否有不能在首页展示的按键 如果有 “更多”键也设置能用
	 */
	private void initKey() {
		buttons.clear();
		buttons.add(mShakeB);
		buttons.add(mWindB);
		buttons.add(mTimeB);
		moreKeys.clear();
		keys = device.getKeys();
		for (int i = 0; i < keys.size(); i++) {
			String cmd = ConvertUtil.getInstance().convertInfraredCmd(keys.get(i).getCodeValue());
			int p = keys.get(i).getKeyNum();
			// Log.i("wmy", "cmdMaps添加一个p = " + p);
			cmdMaps.put(p, cmd);
		}
		for (int i = 0; i < buttons.size(); i++) {
			// Log.i("wmy",
			// "buttons.get(i).getTag() = "
			// + Integer.parseInt(buttons.get(i).getTag()
			// .toString()));
			String cmd = cmdMaps.get(Integer.parseInt(buttons.get(i).getTag().toString()));
			if (cmd == null) {
				setBg(buttons.get(i).getId(), false);
			} else {
				setBg(buttons.get(i).getId(), true);
			}
		}
		for (int i = 0; i < keys.size(); i++) {
			// 如果按键不是温度加和温度减 进行判断
			if (keys.get(i).getKeyNum() != 811 && keys.get(i).getKeyNum() != 812 && keys.get(i).getKeyNum() != 800
					&& keys.get(i).getKeyNum() != 4000) {
				boolean e = false;
				for (Button btn : buttons) {
					int tag = Integer.parseInt(btn.getTag().toString());
					if (tag == keys.get(i).getKeyNum()) {
						e = true;
						// moreKeys.add(keys.get(i));
						break;
					}
				}
				if (!e) {
					boolean e1 = false;
					for (int n = 0; n < moreKeys.size(); n++) {
						if (moreKeys.get(n).getKeyNum() == keys.get(i).getKeyNum()) {
							e1 = true;
						}
					}
					if (!e1) {
						Log.i("wmy", "moreKeys添加 = " + keys.get(i).getKeyNum() + " " + i);
						moreKeys.add(keys.get(i));
					}
				}
			}
		}
		Log.i("wmy", "moreKeys.size() = " + moreKeys.size());
		if (moreKeys.size() > 0) {
			mMoreB.setBackgroundResource(R.drawable.selector_more1);
			mMoreB.setClickable(true);
			// initDialog();
		} else {
			mMoreB.setBackgroundResource(R.drawable.ddd12x);
			mMoreB.setClickable(false);
		}
	}

	private void setBg(int id, boolean e) {
		if (e) {
			switch (id) {
			case R.id.shake_btn:
				mShakeB.setClickable(true);
				mShakeB.setBackgroundResource(R.drawable.selector_shake);
				break;
			case R.id.wind_btn:
				// 838
				mWindB.setClickable(true);
				mWindB.setBackgroundResource(R.drawable.selector_wind_class);
				break;
			case R.id.time_btn:
				// 876
				mTimeB.setClickable(true);
				mTimeB.setBackgroundResource(R.drawable.selector_time);
				break;

			default:
				break;
			}
		} else {
			switch (id) {
			case R.id.shake_btn:
				mShakeB.setBackgroundResource(R.drawable.moshi1x);
				mShakeB.setClickable(false);
				break;
			case R.id.wind_btn:
				// 833
				mWindB.setBackgroundResource(R.drawable.fenglei1x);
				mWindB.setClickable(false);
				break;
			case R.id.time_btn:
				// 876
				mTimeB.setBackgroundResource(R.drawable.naozhong12x);
				mTimeB.setClickable(false);
				break;

			default:
				break;
			}
		}
	}

	private void resetButton(boolean e) {
		if (e) {
			initKey();
			mMoreB.setClickable(true);
		} else {
			for (int i = 0; i < buttons.size(); i++) {
				setBg(buttons.get(i).getId(), false);
			}
			mMoreB.setClickable(false);
			mMoreB.setBackgroundResource(R.drawable.ddd12x);
		}
	}

	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	private void sendCmd(String cmd) {
		if (socket.isLocalSuccess()) {
			socket.sendMqttData(cmd);
		} else {
			SocketManager.getInstance().sendRemoteData(socket.getMac(), DeviceManager.getInstance().getmWlanId(), cmd);
		}
	}

	class KeyAdapter extends BaseAdapter {
		HoldView holdView;
		private int imageResId;
		private int stringResId;

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return moreKeys.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return moreKeys.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View v, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (v == null) {
				v = LayoutInflater.from(RemoteFanActivity.this).inflate(R.layout.item_more_key, null);
				holdView = new HoldView();
				holdView.btn = (Button) v.findViewById(R.id.key_btn);
				v.setTag(holdView);
			} else {
				holdView = (HoldView) v.getTag();
			}
			final Key k = moreKeys.get(position);
			holdView.btn.setTag(k.getKeyNum());
			int content = KeyManager.getInstance().getContentTypeByKeyNum(k.getKeyNum());
			if (content == 0) {
				imageResId = KeyManager.getInstance().getDrawableResId(k.getKeyNum());
				holdView.btn.setBackgroundResource(imageResId);
			} else {
				stringResId = KeyManager.getInstance().getStringResId(k.getKeyNum());
				holdView.btn.setText(stringResId);
			}
			holdView.btn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Log.i("wmy", "点击了" + k.getKeyNum());
					int tag = Integer.parseInt(v.getTag().toString());
					sendCmd(cmdMaps.get(tag));
					vibrator.vibrate(50);
				}
			});

			return v;
		}
	}

	class HoldView {
		private Button btn;
	}

}
